package com.ophiux.cs.application.consult.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ophiux.cs.application.consult.dto.CSConInitRequest;
import com.ophiux.cs.application.consult.dto.CSConInitResponse;
import com.ophiux.cs.application.consult.dto.CSLoginRequest;
import com.ophiux.cs.application.consult.dto.CSLoginResponse;
import com.ophiux.cs.application.consult.dto.CSRegisterResponse;
import com.ophiux.cs.application.consult.service.ICSConInitAppService;
import com.ophiux.cs.application.consult.service.ICSUserLoginAppService;
import com.ophiux.cs.application.consult.service.ICSUserRegisterAppService;
import com.ophiux.cs.application.core.Result;
import com.ophiux.cs.domain.consult.model.entity.CSUser;
import com.ophiux.cs.domain.consult.repositories.IUserInfoRepository;
import com.ophiux.utils.exception.OphiuxRepositoryException;

/**
 * 咨询用户初始化
 * 先判断初始化的用户是否 已经存在
 * 存在：登录
 * 不存在：先注册，在登录
 * @author chenh
 *
 */
@Service("cSConInitAppService")
public class CSConInitAppService implements ICSConInitAppService{

	@Autowired
	IUserInfoRepository cSUserInfoRepository;	//用户信息仓储
	
	@Autowired
	ICSUserRegisterAppService csUserRegisterService;	//咨询用户注册应用
	
	@Autowired
	ICSUserLoginAppService csUserLoginService;	//咨询用户登录应用
	
	@Override
	public Result<CSConInitResponse> ConInit(CSConInitRequest request) {
		
		//初始化
		Result<CSConInitResponse> result = null;
		
		//登录
		Result<CSLoginResponse> csLoginResult = null;
		
		/**参数合法性验证**/
		if(!request.isParamValid()) {
			return Result.fail("", "参数不合法");
		}
		
		//根据账号获取用户信息
		String targetAcc = request.getTARGET_ACC();
		CSUser csUser = null;
		try {
			csUser = cSUserInfoRepository.getCSUserByTargetACC(targetAcc);
		} catch (OphiuxRepositoryException e) {
			e.printStackTrace();
			return Result.fail("", e.getExceptionMessage());
		}
		
		//预先构造登录入参
		//登录
		CSLoginRequest csLoginRequest = new CSLoginRequest();
		csLoginRequest.setTARGET_ACC(targetAcc);
		
		//判断用户是否存在，存在：登录；不存在，先注册，在登录
		if(csUser == null) {
			Result<CSRegisterResponse> regResult = 
					csUserRegisterService.CSRegister(request);
			//注册失败
			if(!regResult.isSuccess()) 
				return Result.fail("", "用户注册失败，失败原因："+regResult.getERROR_CODE());
			
			//注册成功，登录
			csLoginResult = 
					csUserLoginService.CSLogin(csLoginRequest);
		}else {
			//用户存在且有效，登录
			if(!csUser.isValid())  return Result.fail("", "该用户已被禁用");
			//登录
			csLoginResult = 
					csUserLoginService.CSLogin(csLoginRequest);
		}
		//判断是否登录成功
		if(csLoginResult.isSuccess()) {
			CSConInitResponse CSConInitResponse = csLoginResult.getRESPONSE();
			result = Result.success(CSConInitResponse);
		}
		else
			result = Result.fail("", csLoginResult.getERROR_CODE());
		
		return result;
	}

	
}
